package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.help.subform.TransferSubFormHelper;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.SupplierUserDao;
import com.xbongbong.saas.domain.entity.SupplierUserEntity;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.enums.subform.PaymentSheetTeamEnum;
import com.xbongbong.saas.enums.subform.SupplierTeamEnum;
import com.xbongbong.saas.model.SupplierUserModel;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.action.support.WriteRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 供应商负责人
 * @author Jian.Wang
 * @date 2019/1/30 16:41
 * @since v1.0
 * @version v1.0
 */
@Service("SupplierUserModel")
public class SupplierUserModelImpl implements SupplierUserModel{
    @Resource
    private SupplierUserDao supplierUserDao;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private TransferSubFormHelper transferSubFormHelper;

    /**
     * 供应商负责人数据插入
     *
     * @param entity 供应商实体
     * @return Integer
     * @throws XbbException 异常
     * @author Jian.Wang
     * @date 2019/1/30 16:47
     * @since v1.0
     */
    @Override
    public Integer insert(SupplierUserEntity entity) throws XbbException {
        long now = DateUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);
        Integer result = supplierUserDao.insert(entity);
        PaasFormDataEntity paasFormDataEntity = transferSubFormHelper.transferUserTeamToFormData(IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM, entity);
        InsertDTO saveDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM);
        paasEsModel.insert(saveDTO);
//        paasEsModel.insert(entity,IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM,entity.getCorpid(),entity.getId(),entity.getDataId());
        return result;
    }

    /**
     * 供应商负责人数据更新
     *
     * @param entity 供应商实体
     * @return Integer
     * @throws XbbException 异常
     * @author Jian.Wang
     * @date 2019/1/30 16:47
     * @since v1.0
     */
    @Override
    public Integer update(SupplierUserEntity entity) throws XbbException {
        long now = DateUtil.getInt();
        entity.setUpdateTime(now);
        Integer result = supplierUserDao.update(entity);
        PaasFormDataEntity paasFormDataEntity = transferSubFormHelper.transferUserTeamToFormData(IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM, entity);
        InsertDTO saveDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM);
        paasEsModel.update(saveDTO);
//        paasEsModel.update(entity,IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM,entity.getCorpid(),entity.getId(),entity.getDataId());
        return result;
    }

    /**
     * 供应商负责人数据查询多个
     *
     * @param param 参数
     * @return List<SupplierEntityExt>
     * @author Jian.Wang
     * @date 2019/1/30 16:47
     * @since v1.0
     */
    @Override
    public List<SupplierUserEntity> findEntitys(Map<String, Object> param) {
        return supplierUserDao.findEntitys(param);
    }

    /**
     * 供应商负责人数据查询条数
     *
     * @param param 参数
     * @return Integer
     * @author Jian.Wang
     * @date 2019/1/30 16:47
     * @since v1.0
     */
    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return supplierUserDao.getEntitysCount(param);
    }

    @Override
    public List findEntitysWithoutSub(Map<String, Object> param) {
        return null;
    }

    /**
     * 供应商负责人数据单条查询
     *
     * @param key    主键ID
     * @param corpid 公司ID
     * @return Integer
     * @author Jian.Wang
     * @date 2019/1/30 16:47
     * @since v1.0
     */
    @Override
    public SupplierUserEntity getByKey(Long key, String corpid) {
        return supplierUserDao.getByKey(key,corpid);
    }

    /**
     * 查询协同团队基础列表
     *
     * @param map 参数
     * @return 团队
     */
    @Override
    public List<UserTeamEntity> findBaseEntitys(Map<String, Object> map) {
        return supplierUserDao.findBaseEntitys(map);
    }

    @Override
    public Integer save(SupplierUserEntity supplierUserEntity) throws XbbException {
        if (supplierUserEntity.getId() == null || supplierUserEntity.getId() == 0L) {
            return insert(supplierUserEntity);
        } else {
            return update(supplierUserEntity);
        }
    }

    @Override
    public Integer deleteBySupplierIdIn(List<Long> supplierIdIn, String corpid) throws XbbException{
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid",corpid);
        map.put("del",0);
        map.put("supplierIdIn",supplierIdIn);
        List<SupplierUserEntity> supplierUserEntityList = findEntitys(map);
        Integer result = supplierUserDao.deleteBySupplierIdIn(corpid, supplierIdIn);
        for (SupplierUserEntity entity : supplierUserEntityList){
            paasEsModel.delete(entity.getId(), corpid, IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM,entity.getDataId());
        }
        return result;
    }

    @Override
    public List<Long> getDataIdList(String corpid, Integer isMain, List<String> userId) {
        return supplierUserDao.getDataIdList(corpid,isMain,userId);
    }

    @Override
    public void delete(SupplierUserEntity supplierUserEntity) throws XbbException {
        supplierUserEntity.setDel(1);
        supplierUserEntity.setUpdateTime((long) DateUtil.getInt());
        supplierUserDao.update(supplierUserEntity);
        paasEsModel.delete(supplierUserEntity.getId(), supplierUserEntity.getCorpid(), IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM,supplierUserEntity.getDataId());
    }

    @Override
    public List<SupplierUserEntity> getSupplierUserListBySupplierId(String corpid, Long supplierId) {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("del", 0);
        param.put("supplierId", supplierId);
        return findEntitys(param);
    }

    @Override
    public List<String> getSupplierUserIdList(String corpid, List<Long> supplierIds, Integer isMain) {
        return supplierUserDao.getSupplierUserIdListByIn(corpid, supplierIds, isMain);
    }

    @Override
    public void batchUpdateByUserIdIn(String corpid, List<Long> dataIdIn, List<UserTeamEntity> teamEntityList, Integer isMain, Integer del) throws XbbException {
        supplierUserDao.batchUpdateByIdIn(corpid, dataIdIn, isMain, del);
        List<InsertDTO> insertList = new ArrayList<>();
        for (UserTeamEntity userTeamEntity : teamEntityList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM.getType() + "_" + corpid + "_" + userTeamEntity.getId());
            insertDTO.setParent(corpid + "_" + userTeamEntity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(isMain)) {
                map.put(SupplierTeamEnum.getAttrConnectData(SupplierTeamEnum.IS_MAIN), isMain);
            }
            if (Objects.nonNull(del)) {
                map.put(ParameterConstant.DEL, del);
            }
            map.put(FieldTypeEnum.UPDATETIME.getAlias(), DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList);
    }

    @Override
    public void batchUpdateByUserIdIn(String corpid, List<Long> dataIdIn, List<UserTeamEntity> teamEntityList, Integer isMain, Integer del, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        supplierUserDao.batchUpdateByIdIn(corpid, dataIdIn, isMain, del);
        List<InsertDTO> insertList = new ArrayList<>();
        for (UserTeamEntity userTeamEntity : teamEntityList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM.getType() + "_" + corpid + "_" + userTeamEntity.getId());
            insertDTO.setParent(corpid + "_" + userTeamEntity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(isMain)) {
                map.put(SupplierTeamEnum.getAttrConnectData(SupplierTeamEnum.IS_MAIN), isMain);
            }
            if (Objects.nonNull(del)) {
                map.put(ParameterConstant.DEL, del);
            }
            map.put(FieldTypeEnum.UPDATETIME.getAlias(), DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList, refreshPolicy);
    }

    @Override
    public void insertBatch(List<SupplierUserEntity> supplierUserEntityList, boolean isImport) throws XbbException {
        supplierUserDao.insertBatch(supplierUserEntityList);
        List<PaasFormDataEntity> paasFormDataEntities = transferSubFormHelper.transferUserTeamToFormDataList(IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM, supplierUserEntityList);
        //ES数据插入
        List<InsertDTO> insertList = new ArrayList<>();
        for (PaasFormDataEntity paasFormDataEntity : paasFormDataEntities) {
            insertList.add(paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM));
        }

//        for (SupplierUserEntity item : supplierUserEntityList) {
//            InsertDTO insertDTO = new InsertDTO();
//            insertDTO.setEsId(item.getCorpid() + "_" + item.getId());
//            insertDTO.setParent(item.getCorpid() + "_" + item.getDataId());
//            insertDTO.setSource(BeanUtil.convertBean2Map(item));
//            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM);
//            insertList.add(insertDTO);
//        }
        if (isImport) {
            paasEsModel.insertBatch(insertList, WriteRequest.RefreshPolicy.NONE);
        } else {
            paasEsModel.insertBatch(insertList);
        }
    }

    @Override
    public Map<Long, String> batchDeleteById(String corpid, List<Long> removeIdList) throws XbbException{
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid",corpid);
        map.put("del",0);
        map.put("idIn",removeIdList);
        List<SupplierUserEntity> supplierUserEntityList = findEntitys(map);
        supplierUserDao.batchDeleteById(corpid,removeIdList);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        Map<Long,String> supplierUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (SupplierUserEntity entity : supplierUserEntityList){
            supplierUserMap.put(entity.getDataId(),entity.getUserId());
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM.getType() + "_" + corpid + "_" + entity.getId());
            insertDTO.setParent(corpid + "_" + entity.getDataId());
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM);
            insertDTO.setIndex(IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM.getIndex());
            insertDTO.setType(IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM.getType());
            Map<String,Object> sourceMap = new HashMap<>();
            sourceMap.put(StringConstant.UPDATE_TIME, DateTimeUtil.getInt());
            sourceMap.put(StringConstant.DEL, DelEnum.DELETE.getDel());
            insertDTO.setSource(sourceMap);
            insertDTOList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertDTOList);
        return supplierUserMap;
    }

    @Override
    public void deleteBatchUser(List<SupplierUserEntity> supplierUserEntityList, String corpid, Integer del) throws XbbException {
        if (CollectionUtils.isEmpty(supplierUserEntityList)) {
            return;
        }
        List<Long> idList = new ArrayList<>();
        List<InsertDTO> insertDTOList = new ArrayList<>();
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put(StringConstant.UPDATE_TIME, DateTimeUtil.getInt());
        map.put(StringConstant.DEL, del);
        for (SupplierUserEntity entity : supplierUserEntityList){
            idList.add(entity.getId());
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM.getType() + "_" + corpid + "_" + entity.getId());
            insertDTO.setParent(corpid + "_" + entity.getDataId());
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM);
            insertDTO.setIndex(IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM.getIndex());
            insertDTO.setType(IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM.getType());
            insertDTO.setSource(map);
            insertDTOList.add(insertDTO);
        }
        deleteBatch(idList,corpid, del);
        paasEsModel.updateBatch(insertDTOList);
    }

    private Integer deleteBatch(List<Long> list, String corpid, Integer del) throws XbbException{
        return supplierUserDao.deleteBatch(list, corpid, del);
    }

    @Override
    public void updateBatch(List<SupplierUserEntity> supplierUserEntities, String corpid) throws XbbException {
        supplierUserDao.updateBatch(supplierUserEntities, corpid);
        List<PaasFormDataEntity> paasFormDataEntities = transferSubFormHelper.transferUserTeamToFormDataList(IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM, supplierUserEntities);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PaasFormDataEntity paasFormDataEntity : paasFormDataEntities) {
            insertDTOList.add(paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM));
        }
        paasEsModel.updateBatch(insertDTOList);
    }


    /**
     *
     * @Description: 编辑团队成员标签
     * @param supplierUserEntity
     * @return: void
     * @Author: shen.yang
     * @Date: 2022/1/17  14:20
     */
    @Override
    public void editLabel(SupplierUserEntity supplierUserEntity) throws XbbException {
        updateFormTeam(supplierUserEntity);
    }

    /**
     * 更新协同人可编辑权限
     *
     * @param supplierUserEntity
     */
    @Override
    public void updateEditFormPer(SupplierUserEntity supplierUserEntity) throws XbbException {
        updateFormTeam(supplierUserEntity);
    }


    private void updateFormTeam(SupplierUserEntity supplierUserEntity) throws XbbException {
        Long updateTime = DateTimeUtil.getInt();
        supplierUserEntity.setUpdateTime(updateTime);
        supplierUserDao.update(supplierUserEntity);
        InsertDTO insertDTO = new InsertDTO();
        String corpid = supplierUserEntity.getCorpid();
        insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM.getType() + "_" + corpid + "_" + supplierUserEntity.getId());
        insertDTO.setParent(corpid + "_" + supplierUserEntity.getDataId());
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("updateTime", updateTime);
        insertDTO.setSource(map);
        insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM);
        paasEsModel.update(insertDTO);
    }

    /**
     * 批量更新团队的人员为协同人身份以及协同人的可编辑权限
     *
     * @param corpid
     * @param idIn
     * @param teamEntityList
     * @param isMain
     * @param needThrow
     * @throws XbbException
     */
    @Override
    public void batchUpdateCoAndPerByUserIdIn(String corpid, List<Long> idIn, List<UserTeamEntity> teamEntityList, Integer isMain, boolean needThrow) throws XbbException {
        batchUpdateCoAndPerByUserIdIn(corpid, idIn, teamEntityList, isMain, needThrow, WriteRequest.RefreshPolicy.WAIT_UNTIL);
    }

    @Override
    public void batchUpdateCoAndPerByUserIdIn(String corpid, List<Long> idIn, List<UserTeamEntity> teamEntityList, Integer isMain, boolean needThrow, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        Integer formPermission = teamEntityList.get(BasicConstant.ZERO).getFormPermission();
        supplierUserDao.batchUpdateCoAndPerByUserIdIn(corpid, idIn, isMain, formPermission);
        List<InsertDTO> insertList = new ArrayList<>();
        for (UserTeamEntity userTeamEntity : teamEntityList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM.getType() + "_" + corpid + "_" + userTeamEntity.getId());
            insertDTO.setParent(corpid + "_" + userTeamEntity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(isMain)) {
                JSONObject object = new JSONObject();
                object.put(PaymentSheetTeamEnum.IS_MAIN.getDataAttr(), isMain);
                map.put(StringConstant.JSON_DATA, object);
            }
            map.put(FieldTypeEnum.UPDATETIME.getAlias(), DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_SUPPLIER_TEAM);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList, refreshPolicy, needThrow);
    }

}
